package com.lmm.lcbusiness.lcbusiness.pages.richtxt.main;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.lmm.dresswisdom.lmmframe.components.alert.TWActionSheet;
import com.lmm.dresswisdom.lmmframe.util.LogUtils;
import com.lmm.dresswisdom.lmmframe.util.ToastUtils;
import com.lmm.lcbusiness.lcbusiness.AppBaseActivity;
import com.lmm.lcbusiness.lcbusiness.R;
import com.lmm.lcbusiness.lcbusiness.cominterface.UploadCallBack;
import com.lmm.lcbusiness.lcbusiness.config.ConfigValue;
import com.lmm.lcbusiness.lcbusiness.pages.richtxt.RichTxtAdapter;
import com.lmm.lcbusiness.lcbusiness.pages.richtxt.RichTxtEditActivity;
import com.lmm.lcbusiness.lcbusiness.pages.richtxt.RichTxtModel;
import com.lmm.lcbusiness.lcbusiness.pages.richtxt.RichViewActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xmgong
 * @date 2017/11/30
 */
@Route(path = "/app/richtxt/main")
public class RichTxtActivity extends AppBaseActivity implements View.OnClickListener, RichTxtContract.IView,
        BaseQuickAdapter.OnItemChildClickListener, InvokeListener, TakePhoto.TakeResultListener {

    RichTxtPresent mPresent;
    public static final String ActivityTitleKey = "title";
    public static final String ActivityRichTxtKeyStr = "richtxt_str";
    LinearLayout linAdd;
    RecyclerView mRecyclerView;
    RichTxtAdapter mRichTxtAdapter;
    List<RichTxtModel> mRichTxtModelList = new ArrayList<>();
    private final int ReqEditText = 61;
    int curPosition = 0;
    //添加富文本对话框
    Dialog optionDialog = null;
    //图片选择对话框
    Dialog imgDialog = null;
    //拍照后图片
    File takePhotoImgFile;
    TakePhoto takePhoto;
    /**
     * 文件夹名称
     */
    String QiNiuTag = "richtxt";
    String QiNiuToken = "";


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_richtxt);

        mPresent = new RichTxtPresent(this);

        linAdd = findViewById(R.id.lin_richtxt_add);
        mRecyclerView = findViewById(R.id.recy);
        if (getIntent().hasExtra(ActivityTitleKey)) {
            setActionBarTitle(getIntent().getStringExtra(ActivityTitleKey));
        }
        if (getIntent().hasExtra(ActivityRichTxtKeyStr)) {
            String res = getIntent().getStringExtra(ActivityRichTxtKeyStr);
            try {
                JSONArray jsonArray = new JSONArray(res);
                RichTxtModel rtm = null;
                JSONObject item = null;
                for (int i = 0; i < jsonArray.length(); i++) {
                    rtm = new RichTxtModel();
                    item = (JSONObject) jsonArray.get(i);
                    rtm.setRichType(item.getInt("type"));
                    rtm.setRichValue(item.getString("value"));
                    mRichTxtModelList.add(rtm);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (getIntent().hasExtra("filetag")) {
            QiNiuTag = getIntent().getStringExtra("filetag");
        }

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        linAdd.setOnClickListener(this);
        mRichTxtAdapter = new RichTxtAdapter(mRichTxtModelList);
        mRecyclerView.setAdapter(mRichTxtAdapter);
        mRichTxtAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

                if (mRichTxtModelList.get(i).getItemType() == RichTxtModel.RichType_Txt) {
                    //跳转到编辑页面
                    String value = mRichTxtModelList.get(i).getRichValue();
                    Intent mintent = new Intent(RichTxtActivity.this, RichTxtEditActivity.class);
                    mintent.putExtra("richmodel", value);
                    mintent.putExtra("index", i);
                    startActivityForResult(mintent, ReqEditText);
                }
            }
        });
        mRichTxtAdapter.setOnItemChildClickListener(this);
        imgDialog = TWActionSheet.create(this, "图片选择", new String[]{"来自相册", "拍照"}, new ImageDialogItemClick());
        takePhotoImgFile = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        mPresent.getTokenAction();
    }

    @Override
    public void onClick(View view) {
        if (view == linAdd) {
            addRichView(mRichTxtAdapter.getData().size());
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int i) {
        LogUtils.write("position:" + String.valueOf(i));
        switch (view.getId()) {
            case R.id.lin_richtxt_add:
                addRichView(i + 1);
                break;
            case R.id.lin_richtxt_del:
                delRichTxt(i);
                break;
            case R.id.lin_richtxt_up:
                upRichTxt(i);
                break;
            default:
                break;
        }
    }


    /**
     * 添加富文本
     *
     * @param position
     */
    private void addRichView(int position) {
        curPosition = position;
        if (optionDialog == null) {
            optionDialog = TWActionSheet.create(this, "选择", new String[]{"文字", "图片"}, new OptionDialogItemClick());
        }
        optionDialog.show();
    }


    private void delRichTxt(int position) {
        mRichTxtModelList.remove(position);
        mRichTxtAdapter.notifyItemRemoved(position);
    }


    private void upRichTxt(int position) {
        if (position == 0) {
            return;
        }
        mRichTxtModelList.add(position - 1, mRichTxtModelList.remove(position));
        mRichTxtAdapter.notifyDataSetChanged();
    }


    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ReqEditText) {
            if (resultCode == RESULT_OK) {
                String value = data.getStringExtra("value");
                int index = data.getIntExtra("index", -1);
                if (index == -1) {
                    //新增
                    RichTxtModel tx = new RichTxtModel();
                    tx.setRichType(RichTxtModel.RichType_Txt);
                    tx.setRichValue(value);
                    mRichTxtModelList.add(curPosition, tx);
                    mRichTxtAdapter.notifyDataSetChanged();
                } else {
                    mRichTxtModelList.get(index).setRichValue(value);
                    mRichTxtAdapter.notifyItemChanged(index);
                }
            }
        }
    }


    @Override
    public void takeSuccess(TResult result) {
        if (result.getImages().size() > 0) {
            for (TImage image : result.getImages()) {
                showDefaultDialog();
                mPresent.uploadImgAction(QiNiuToken, QiNiuTag, new File(image.getOriginalPath()), new UploadCallBack() {
                    @Override
                    public void uploadFinish(String netaddress) {
                        RichTxtModel rtm = new RichTxtModel();
                        rtm.setRichType(RichTxtModel.RichType_Image);
                        rtm.setRichValue(ConfigValue.IMGPrefix_Https_QN + netaddress);
                        mRichTxtModelList.add(curPosition, rtm);
                        mRichTxtAdapter.notifyDataSetChanged();
                        hideDefaultDialog();
                    }
                });
            }
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        ToastUtils.showToastShort(msg);
    }

    @Override
    public void takeCancel() {
    }

    @Override
    public void setQNToken(String token) {
        if (token != null && token.length() > 0) {
            QiNiuToken = token;
        }
    }

    class OptionDialogItemClick implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if (i == 0) {
                //文字
                Intent mintent = new Intent(RichTxtActivity.this, RichTxtEditActivity.class);
                startActivityForResult(mintent, ReqEditText);
            } else {
                //图片
                if (imgDialog != null) {
                    imgDialog.show();
                }
            }
            optionDialog.dismiss();
        }
    }


    class ImageDialogItemClick implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if (i == 0) {
                getTakePhoto().onPickFromGalleryWithCrop(Uri.fromFile(takePhotoImgFile),
                        new CropOptions.Builder().setOutputX(1000).setOutputX(1000).create());
            } else {
                getTakePhoto().onPickFromCaptureWithCrop(Uri.fromFile(takePhotoImgFile),
                        new CropOptions.Builder().setOutputX(1000).setOutputY(1000).create());
            }
            imgDialog.dismiss();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    private InvokeParam invokeParam;

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_richtxt_save, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        if (item.getItemId() == R.id.action_preview) {
            Intent mintent = new Intent(RichTxtActivity.this, RichViewActivity.class);
            mintent.putExtra(RichViewActivity.RichDataKey, (Serializable) mRichTxtModelList);
            startActivity(mintent);
        } else if (item.getItemId() == R.id.action_save) {
            saveRichTxt();
        }
        return true;
    }


    private void saveRichTxt() {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = null;
        for (RichTxtModel rtm : mRichTxtModelList) {
            jsonObject = new JSONObject();
            try {
                jsonObject.put("type", rtm.getRichType());
                jsonObject.put("value", rtm.getRichValue());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray.put(jsonObject);
        }

        Intent mintent = new Intent();
        mintent.putExtra("value", jsonArray.toString());
        setResult(RESULT_OK, mintent);
        finish();
    }
}
